import argparse
import subprocess
import os
import json

class CheckModule:
    def __init__(self, json_file):
        # 从json文件中读取数据
        with open(json_file, 'r') as f:
            self.data = json.load(f)

    def check_support(self):
        results = {}
        for row in self.data:
            feature = row['feature']
            support_method = row['checksupportmethod']
            expected_support = row['checksupporttrue']

            #执行检测命令
            support_result = self.run_command(support_method)
            if support_result.strip() != expected_support.strip():
                results[feature] = self.get_support_info(feature)
            else:
                results[feature] = "Feature supported."
                enabled_result = self.check_enable(row)
                results[feature] += "\n" + enabled_result
        return results

    def check_enable(self, row):
        feature = row['feature']
        enable_method = row['checkenablemethod']
        expected_enable = row['checkenabletrue']

        #执行使能检测命令
        if enable_method == "enable in guest":
            return f"Check enable in guest: {row['enablemethod']}"
        
        enable_result = self.run_command(enable_method)
        if enable_result.strip() == expected_enable.strip():
            return f"Feature if enabled."
        else:
            return f"To enable the feature, use: {row['enablemethod']}"
    
    @staticmethod
    def run_command(command):
        try:
            result = subprocess.check_output(command, shell=True, text=True)
            return result
        except subprocess.CalledProcessError as e:
            return str(e)
    
    def get_support_info(self, feature):
        return f"Feature '{feature}' is not supported. Please check the necessary patches."

class VirtCheck:
    def __init__(self, mode):
        #使用内置的JSON文件
        if mode == "host":
            json_file = os.path.join(os.path.dirname(__file__), 'data', 'feature-host.json')
        if mode == "guest":
            json_file = os.path.join(os.path.dirname(__file__), 'data', 'feature-guest.json')
        self.check_module = CheckModule(json_file)
        self.mode = mode
    
    def run(self):
        results = self.check_module.check_support()
        for feature, result in results.items():
            print(f"{feature}: {result}")

def main():
    parser = argparse.ArgumentParser(description="Virtualization Feature Checker")
    parser.add_argument('--host', action='store_true', help="check on host")
    parser.add_argument('--guest', action='store_true', help="check on guest")
    args = parser.parse_args()

    mode = "host" if args.host else "guest" if args.guest else None
    if not mode:
        print("Please specify either --host or --guest.")
        return

    checker = VirtCheck(mode)
    checker.run()

if __name__ == "__main__":
    main()





